//
//  WKPhoneAuthViewController.m
//  Walk
//
//  Created by cesh on 16/9/28.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKPhoneAuthViewController.h"
#import "WKBubbleViewController.h"
@interface WKPhoneAuthViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *back;

@property (weak, nonatomic) IBOutlet UITextField *numberTextField;
@property (weak, nonatomic) IBOutlet UITextField *verTextField;
@property (weak, nonatomic) IBOutlet UIButton *verBtn;

@property (strong, nonatomic) NSTimer *timer;

@property (assign, nonatomic) NSInteger count;

@end

@implementation WKPhoneAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.count = 60;
    self.back.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapOnBack = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pop)];
    [self.back addGestureRecognizer:tapOnBack];
    
    //点击背景退出键盘
    UITapGestureRecognizer *tapOnBg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resighKeyboard)];
    [self.view addGestureRecognizer:tapOnBg];
    //获取验证码的按钮事件
    [self.verBtn addTarget:self action:@selector(clickVerBtn:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)pop {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)resighKeyboard {
    [self.numberTextField resignFirstResponder];
    [self.verTextField resignFirstResponder];
}

- (void)clickVerBtn:(UIButton *)button {
    [self.verBtn setTitle:[NSString stringWithFormat:@"获取中(%li)", (long)self.count] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:0x9b / 255.0 green:0x9b / 255.0 blue:0x9b / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [button setEnabled:NO];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
}

- (void)countDown {
    self.count--;
    [self.verBtn setTitle:[NSString stringWithFormat:@"获取中(%li)", (long)self.count] forState:UIControlStateNormal];
    //事件倒数为0则重置
    if (self.count == -1) {
        [self.verBtn setEnabled:YES];
        [self.verBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.timer invalidate];
        self.timer = nil;
        self.count = 3;
    }
}

- (IBAction)getCode:(id)sender {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    [mgr POST:[NSString stringWithFormat:@"%@Sms/sendCode", URL] parameters:@{@"phone" : self.numberTextField.text,
                                                                              @"type" : @"2"} progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"获取验证码 %@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取验证码 失败%@", error);
        [WKPopView showWithType:PopViewTypeTimeOut];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
        });
    }];
}
- (IBAction)bind:(id)sender {
    if ([self.numberTextField.text length] == 0) {
        return;
    }
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    NSString *token = [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"];
    
    [mgr POST:[NSString stringWithFormat:@"%@Login/bindPhone", URL] parameters:@{@"phone" : self.numberTextField.text,
                                                                                 @"token" : token,
                                                                                 @"code" : self.verTextField.text} progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"手机绑定 %@", responseObject);
        //重新设置环信账号和密码
        
        NSMutableDictionary *userinfo = [NSMutableDictionary dictionaryWithContentsOfFile:userInfoPath];
        [userinfo setValue:responseObject[@"data"][@"data"][@"nickname"] forKey:@"nickname"];
        [userinfo setValue:responseObject[@"data"][@"data"][@"sex"] forKey:@"sex"];
        
        NSString *birthday = responseObject[@"data"][@"data"][@"birthday"];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[birthday integerValue]];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy/MM/dd"];
        NSString *strDate = [dateFormatter stringFromDate:date];
        [userinfo setValue:strDate forKey:@"birthday"];
        
        [userinfo setValue:responseObject[@"data"][@"data"][@"describe"] forKey:@"describe"];
        [userinfo setValue:responseObject[@"data"][@"data"][@"school"][@"name"] forKey:@"school"];
        [userinfo setValue:responseObject[@"data"][@"data"][@"major"][@"name"] forKey:@"major"];
        [userinfo setValue:responseObject[@"data"][@"data"][@"token"] forKey:@"token"];
        [userinfo setValue:responseObject[@"data"][@"data"][@"hx_user"] forKey:@"hx_user"];
        [userinfo setValue:responseObject[@"data"][@"data"][@"hx_pwd"] forKey:@"hx_pwd"];
        [userinfo setValue:responseObject[@"data"][@"data"][@"phone"] forKey:@"phoneNumber"];
        [userinfo writeToFile:userInfoPath atomically:YES];
        NSLog(@"绑定手机后 userinfo %@",userinfo);
        [self resighKeyboard];
        [WKPopView showWithType:PopViewTypeBindSuccess];
        
        //如果用户数据是完整的则直接进入气泡界面
        NSString *is_full = responseObject[@"data"][@"is_full"];
        if ([is_full isEqualToString:@"1"]) {
            WKBubbleViewController *bubbleVC = [[WKBubbleViewController alloc]init];
            CATransition *anim = [CATransition animation];
            anim.type = @"rippleEffect";
            anim.duration = 1.0;
            [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
            
            [UIApplication sharedApplication].keyWindow.rootViewController = bubbleVC;
            //设置完个人资料之后，设置为已登录，以便下一次直接进入气泡界面
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"didLogin"];
        }
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
            //代理逆传
            if ([self.delegate respondsToSelector:@selector(getPhoneNumber:)]) {
                [self.delegate getPhoneNumber:self.numberTextField.text];
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"手机绑定 失败%@", error);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
        });
    }];
}


@end
